package com.godenwater.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.*;
import com.aliyuncs.dysmsapi.transform.v20170525.SendSmsResponseUnmarshaller;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by li on 2018-2-24.
 */
public class SmsUtil {
    public static final String CODE_OK = "OK";

    public static final Long SEND_STATUS_WAITING_RECEIPT = 1L;
    public static final Long SEND_STATUS_FAILURE = 2L;
    public static final Long SEND_STATUS_SUCCESS = 3L;

    private static final String product = "Dysmsapi";
    private static final String domain = "dysmsapi.aliyuncs.com";
    private static final String endpointName = "cn-hangzhou";
    private static final String regionId = "cn-hangzhou";

    private static final String accessKeyId = "LTAIcedbS4TWjMl3";
    private static final String accessKeySecret = "Pm7ZFyf195buPjH7YdxZGSbCadEX6p";

//    private static final String signName = "河长制";
//    private static final String templateCode = "SMS_137545086";

    private static final SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");

    static {
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
    }

    public static SendSmsResponse send(String mobile, String templateParam, String outId,String templateCode,String signName) throws ClientException {

        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(endpointName, regionId, product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(mobile);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setTemplateParam(templateParam);
        request.setOutId(outId);

        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }


    public static QuerySendDetailsResponse query(String mobile, String bizId) throws ClientException {

        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint(endpointName, regionId, product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        request.setPhoneNumber(mobile);
        request.setBizId(bizId);
        request.setSendDate(ft.format(new Date()));
        request.setPageSize(10L);
        request.setCurrentPage(1L);

        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }
    public static String genVerifyCode(int length) {
        String chars = "0123456789";
        StringBuilder sb = new StringBuilder();
        Random rd = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(rd.nextInt(chars.length() - 1)));
        }
        System.out.println("------------ genVerifyCode(): " + sb.toString());
        return sb.toString();
    }
    /**
     *
     * 群发
     * */
    public static SendBatchSmsResponse sendQun(String phoneNumberJson,String signNameJson,String paramJson,String templateCode)throws Exception{
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendBatchSmsRequest request = new SendBatchSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持JSON格式的批量调用，批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        request.setPhoneNumberJson(phoneNumberJson);
        //必填:短信签名-支持不同的号码发送不同的短信签名
        request.setSignNameJson(signNameJson);

        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        request.setTemplateParamJson(paramJson);

        //请求失败这里会抛ClientException异常
        SendBatchSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }
    /**
     * Just for test.
     */
    public static void main(String[] args) throws ClientException, InterruptedException {
        String mobile = "15810057885";
        // Send the message.
        SendSmsResponse response = send(mobile, "4321", "1234567890","SMS_137545086","金水云平台");
        System.out.println("Response of send ----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());

        Thread.sleep(3000L);

        // Query the details.
        if (response.getCode() != null && response.getCode().equals(CODE_OK)) {
            QuerySendDetailsResponse querySendDetailsResponse = query(mobile, response.getBizId());
            System.out.println("Response of query ----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
            for (int i = 0; i < querySendDetailsResponse.getSmsSendDetailDTOs().size(); ++i) {
                QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO = querySendDetailsResponse.getSmsSendDetailDTOs().get(i);
                System.out.println("SmsSendDetailDTO[" + i + "]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
        }
    }
}
